import os

from fastapi import Depends, FastAPI
from fastapi_pagination import add_pagination


def configure_h5_router(app: FastAPI, prefix=""):
    """配置前台路由"""
    from forward.dependencies.verify import h5_login_verify

    from .routers import admin, article, index, login, sms, upload, user
    from .routers.lucky.activity import activity
    from .routers.lucky.code import code
    from .routers.lucky.merchant import merchant
    from .routers.lucky.order import order

    # front 依赖
    front_deps = [Depends(h5_login_verify)]

    # front
    app.include_router(index.router, prefix=prefix, dependencies=front_deps)
    app.include_router(upload.router, prefix=prefix, dependencies=front_deps)
    app.include_router(article.router, prefix=prefix, dependencies=front_deps)
    app.include_router(login.router, prefix=prefix, dependencies=front_deps)
    app.include_router(user.router, prefix=prefix, dependencies=front_deps)
    app.include_router(sms.router, prefix=prefix, dependencies=front_deps)
    app.include_router(activity, prefix=prefix + "/lucky", dependencies=front_deps)
    app.include_router(order, prefix=prefix + "/lucky", dependencies=front_deps)
    app.include_router(code, prefix=prefix + "/lucky", dependencies=front_deps)
    app.include_router(merchant, prefix=prefix + "/lucky", dependencies=front_deps)
    app.include_router(admin.router, prefix=prefix + "/lucky", dependencies=front_deps)


def configure_middleware(app: FastAPI):
    """配置中间件"""
    from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware

    from forward.middlewares.init_cors import init_cors_middleware
    from forward.middlewares.init_time_out import init_timeout_middleware

    app.add_middleware(ProxyHeadersMiddleware)
    init_cors_middleware(app)
    init_timeout_middleware(app)


def configure_static(app: FastAPI):
    """配置静态资源"""
    from fastapi.staticfiles import StaticFiles

    from forward.config import get_settings

    settings = get_settings()
    # 上传路径创建
    if not os.path.exists(settings.upload_directory):
        os.makedirs(settings.upload_directory)
    # 上传路径配置
    app.mount(
        settings.upload_prefix,
        StaticFiles(directory=settings.upload_directory),
        name="upload",
    )
    # 静态资源路径配置
    if settings.enabled_static:
        app.mount(
            settings.static_path,
            StaticFiles(directory=settings.static_directory),
            name="static",
        )


def create_h5() -> FastAPI:
    """创建FastAPI前台应用,并初始化"""
    from forward.exceptions.global_exc import configure_exception

    app = FastAPI()
    configure_exception(app)
    configure_h5_router(app)
    configure_middleware(app)
    add_pagination(app)
    return app
